package edu.tgc.web.controller.system;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.abyss.common.exception.ServiceException;
import org.abyss.common.web.controller.easyui.CommonCrudEasyUiController;
import org.abyss.common.web.controller.easyui.EasyuiResultBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.tgc.entity.system.SysDept;
import edu.tgc.entity.system.SysDuty;
import edu.tgc.entity.system.SysPosition;
import edu.tgc.service.system.SysDeptService;
import edu.tgc.service.system.SysPositionService;
import edu.tgc.web.form.system.SysDeptForm;
import edu.tgc.web.form.system.SysPositionForm;

@Controller
@RequestMapping(value = "sys/position")
public class SysPositionController extends CommonCrudEasyUiController<SysPosition, UUID, SysPositionForm> {

    @Autowired
    protected SysDeptController sysDeptController;

    @Autowired
    protected SysDeptService sysDeptService;
    @Autowired
    protected SysPositionService sysPositionService;

    @Override
    protected void buildIgnoreProperties(Collection<String> ignoreProperties) {
        ignoreProperties.add("duties");
        ignoreProperties.add("depts");
        ignoreProperties.add("userDepts");
    }

    public List<Map<String, Object>> buildPositionList(UUID deptId, Collection<SysPosition> positions) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysPosition position : positions) {
            list.add(buildPositionNode(deptId, position));
        }
        return list;
    }

    public Map<String, Object> buildPositionNode(UUID deptId, SysPosition posistion) {
        Map<String, Object> NodeMap = new HashMap<>();
        NodeMap.put("id", deptId.toString() + "_" + posistion.getId().toString());
        NodeMap.put("name", posistion.getName());
        NodeMap.put("enabled", posistion.getEnabled());
        NodeMap.put("iconCls", "icon-position");
        return NodeMap;
    }

    @ResponseBody
    @RequestMapping(value = "dept", method = RequestMethod.POST)
    public Object dept(SysDeptForm form, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return EasyuiResultBuilder.buildAjaxResultError(bindingResult.getGlobalError().getDefaultMessage());
        } else {
            try {
                this.sysPositionService.setDepts(form.getId(), form.getDeptIds());
            } catch (ServiceException e) {
                return EasyuiResultBuilder.buildAjaxResultError(e.getMessage());
            }
        }
        return EasyuiResultBuilder.buildAjaxResult();
    }

    @ResponseBody
    @RequestMapping(value = "duty", method = RequestMethod.POST)
    public Object duty(SysPositionForm form, BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return EasyuiResultBuilder.buildAjaxResultError(bindingResult.getGlobalError().getDefaultMessage());
        } else {
            try {
                this.sysPositionService.setDuties(form.getId(), form.getDutyIds());
            } catch (ServiceException e) {
                return EasyuiResultBuilder.buildAjaxResultError(e.getMessage());
            }
        }
        return EasyuiResultBuilder.buildAjaxResult();
    }

    @ResponseBody
    @RequestMapping(value = "dept/selected")
    public Object getDepts(String joinIds) {
        Set<SysDept> result = new HashSet<>();
        if (joinIds != null) {
            for (String entityId : joinIds.split(",")) {
                SysPosition entity = this.baseService.getById(UUID.fromString(entityId));
                if (entity != null) {
                    result.addAll(entity.getDepts());
                }
            }
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "duty/selected")
    public Object getDuties(String joinIds) {
        Set<SysDuty> result = new HashSet<>();
        if (joinIds != null) {
            for (String entityId : joinIds.split(",")) {
                SysPosition entity = this.baseService.getById(UUID.fromString(entityId));
                result.addAll(entity.getDuties());
            }
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "treeGrid")
    public Collection<Map<String, Object>> treeGrid(SysDeptForm form, BindingResult bindingResult, Sort sort, Model model) {
        return treeGridWithPosition(this.sysDeptController.treeGrid(form, bindingResult, sort, model));
    }

    @SuppressWarnings("unchecked")
    public Collection<Map<String, Object>> treeGridWithPosition(Collection<Map<String, Object>> list) {
        for (Map<String, Object> entityMap : list) {
            UUID id = (UUID) entityMap.get("id");
            ArrayList<Object> children = new ArrayList<>();
            children.addAll(buildPositionList(id, this.sysDeptService.getPositions(id)));
            List<Map<String, Object>> deptChildren = (List<Map<String, Object>>) entityMap.get("children");
            if (!deptChildren.isEmpty()) {
                treeGridWithPosition(deptChildren);
            }
            children.addAll(deptChildren);
            entityMap.put("children", children);
        }
        return list;
    }

}
